package com.tsmti.listener;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.tsmti.basicdata.entity.*;
import com.tsmti.basicdata.service.*;
import com.tsmti.business.entity.PimsSysPathology;
import com.tsmti.business.service.PimsSysPathologyService;
import com.tsmti.core.common.constant.RedisConstants;
import com.tsmti.core.util.MessageUtils;
import com.tsmti.core.util.RedisUtils;
import com.tsmti.core.util.SpringContextUtils;
import com.tsmti.system.entity.*;
import com.tsmti.system.service.*;
import com.tsmti.util.UserUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.web.context.WebApplicationContext;
import javax.servlet.ServletContext;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @Package：com.tsmti.core.listener
 * @Class：WebStartInitListener
 * @Description： 启动
 * @Author：zcw
 * @Date：Created in 2018/2/28 10:37
 * @Company:
 * @Version：
 * @Modified By:
 */
public class BaseWebStartInitListener implements ApplicationListener<ContextRefreshedEvent> {
    protected org.slf4j.Logger logger = LoggerFactory.getLogger(getClass());
    private static DataDictionaryService dataDictionaryService = SpringContextUtils.getBean(DataDictionaryService.class);
    private static UserService userService = SpringContextUtils.getBean(UserService.class);
    private static OrganizationService organizationService = SpringContextUtils.getBean(OrganizationService.class);
    private static MessagePropertyService messagePropertyService = SpringContextUtils.getBean(MessagePropertyService.class);
    private static SystemParameterService systemParameterService = SpringContextUtils.getBean(SystemParameterService.class);
    private static DoctorInformationService doctorInformationService = SpringContextUtils.getBean(DoctorInformationService.class);
    private static WardInformationService wardInformationService = SpringContextUtils.getBean(WardInformationService.class);
    private static DataSourceService dataSourceService = SpringContextUtils.getBean(DataSourceService.class);
    private static ServiceInfoService serviceInfoService = SpringContextUtils.getBean(ServiceInfoService.class);
    private static DeptInfomationService deptInfomationService = SpringContextUtils.getBean(DeptInfomationService.class);
    private static PimsSysPathologyService pimsSysPathologyService = SpringContextUtils.getBean(PimsSysPathologyService.class);
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        ApplicationContext applicationContext = event.getApplicationContext();
        WebApplicationContext webApplicationContext = (WebApplicationContext) applicationContext;
        ServletContext servletContext = webApplicationContext.getServletContext();
        String webRoot = servletContext.getContextPath();
        logger.info("加载 servlet...");
        //Web根目录
        servletContext.setAttribute("webRoot", webRoot);
        logger.info("Web根目录:" + servletContext.getAttribute("webRoot"));
        //资态资源根目录
        servletContext.setAttribute("resRoot", webRoot + "/statics");
        logger.info("资态资源根目录:" + servletContext.getAttribute("resRoot"));
        // 需要执行的逻辑代码，当spring容器初始化完成后就会执行该方法。
        printKeyLoadMessage();
        //加载缓存
        initDictCache();
        initBasicDataCache();
    }

    /**
     * 获取Key加载信息
     */
    public boolean printKeyLoadMessage() {
        StringBuilder sb = new StringBuilder();
        sb.append("\r\n======================================================================\r\n");
        sb.append("\r\n    欢迎使用 " + MessageUtils.getMessage("platform.name") + " " + MessageUtils.getMessage("platform.version") + "  - " + MessageUtils.getMessage("platform.copyright") + "  " + MessageUtils.getMessage("platform.website") + "\r\n");
        sb.append("\r\n======================================================================\r\n");
        System.out.println(sb.toString());
        return true;
    }

    /**
     * 加载字典缓存至redis
     */
    public void initDictCache() {
        Map<String, List<DataDictionary>> dataDictionaryMap = new HashMap<String, List<DataDictionary>>(16);
        if (dataDictionaryMap == null || dataDictionaryMap.size() <= 0) {
            List<DataDictionary> dictionaryList = dataDictionaryService.listByOrder();
            //list按group分组
            for (DataDictionary dict : dictionaryList) {
                List<DataDictionary> dictList = null;
                if (dataDictionaryMap != null) {
                    dictList = dataDictionaryMap.get(dict.getGroupCode());
                }
                if (dictList != null) {
                    dictList.add(dict);
                } else {
                    dataDictionaryMap.put(dict.getGroupCode(), Lists.newArrayList(dict));
                }
            }
            try {
                RedisUtils.setObject(RedisConstants.DICTIONARY_CACHE, dataDictionaryMap);
            } catch (Exception e) {
                logger.warn("加载字典缓存错误!", e);
            }
        }
    }

    /**
     * 加载其他基础数据缓存
     */
    public void initBasicDataCache() {
        List<User> userList = userService.list();
        List<User> phyUserList = userService.list("userJobType",1);
        List<User> tecUserList = userService.list("userJobType",2);
        List<Organization> organizationList = organizationService.list();
        List<MessageProperty> messagePropertyList = messagePropertyService.list();
        List<SystemParameter> systemParameterList = systemParameterService.list();
        List<DoctorInformation> doctorInformationList = doctorInformationService.list();
        DetachedCriteria detachedCriteria = DetachedCriteria.forClass(DoctorInformation.class);
        detachedCriteria.add(Restrictions.ge("jobLevel",2));
        List<DoctorInformation> doctorList = doctorInformationService.list(detachedCriteria);
        List<WardInformation> wardInformationList = wardInformationService.list();
        List<DataSource> datasSourceList = dataSourceService.list();
        List<ServiceInfo> serviceInfoList = serviceInfoService.list();
        List<DeptInfomation> deptInfomationList = deptInfomationService.list();
        List<PimsSysPathology> sysPathologyList = pimsSysPathologyService.list();
        try {
            RedisUtils.setRedisToMap(RedisConstants.USER_CACHE,"userName", userList);
            RedisUtils.setRedisToMap(RedisConstants.PHY_USER_CACHE,"userName", phyUserList);
            RedisUtils.setRedisToMap(RedisConstants.TEC_USER_CACHE,"userName", tecUserList);
            RedisUtils.setRedisToMap(RedisConstants.ORGANIZATION_CACHE,"code", organizationList);
            RedisUtils.setRedisToMap(RedisConstants.LABEL_CACHE,"code", messagePropertyList);
            RedisUtils.setRedisToMap(RedisConstants.SYSTEMPARAMETER_CACHE,"paramName", systemParameterList);
            RedisUtils.setRedisToMap(RedisConstants.DOCTORANDNURSE_CACHE,"code", doctorInformationList);
            RedisUtils.setRedisToMap(RedisConstants.DOCTOR_CACHE,"code", doctorList);
            RedisUtils.setRedisToMap(RedisConstants.WARD_CACHE,"code", wardInformationList);
            RedisUtils.setRedisToMap(RedisConstants.DEPT_CACHE,"code", deptInfomationList);
            RedisUtils.setObject(RedisConstants.DATASOURCE_CACHE, JSON.toJSONString(datasSourceList));
            RedisUtils.setObject(RedisConstants.SERVICEINFO_CACHE, JSON.toJSONString(serviceInfoList));
            RedisUtils.setRedisToMap(RedisConstants.SYS_PATHOLOGY, "id",sysPathologyList);
        }catch (Exception e){
            logger.warn("加载缓存错误!",e);
        }
    }
}
